// 第三JS方库
import { useHistory } from 'react-router-dom'
import { http } from '@/utils/http'
import { useDispatch } from 'react-redux'
import { login, getCode } from '@/store/actions/login'
import { AxiosError } from 'axios'
// 组件库
import { Button, NavBar, Form, Input, Toast } from 'antd-mobile'
// 自定义组件

// css
import styles from './Login.module.scss'
import { useEffect, useRef, useState } from 'react'
import { InputRef } from 'antd-mobile/es/components/input'

type LoginForm = {
  mobile: string
  code: string
}

export const Login = (props: any) => {
  const dispatch = useDispatch()
  const history = useHistory()
  // http.get('/channels')
  // console.log('使用hook获取history', history)
  // console.log('倍Route增强后的login组件', props.history)
  // console.log(props.history === history) // true

  // 返回按钮
  const back = () => {
    Toast.show({
      content: '🐖',
      duration: 1000,
      afterClose: () => {
        // 返回首页
        history.go(-1)
      },
    })
  }

  // 表单提交
  const onFinish = async (values: LoginForm) => {
    // console.log(values)
    // 准备发起请求
    try {
      await dispatch(login(values))
      // 登录成功提示后，跳转到home页面
      Toast.show({
        content: '登录成功',
        duration: 600,
        afterClose: () => {
          // 返回首页
          history.replace('/layout')
        },
      })
    } catch (e) {
      // e 是未知类型，将错误类型转为AxiosError
      const error = e as AxiosError<{ data: object; message: string }>
      console.log(error)
      Toast.show(error.response?.data.message ?? '网络错误')
    }
  }

  const [form] = Form.useForm()

  // 动态获取验证码
  const mobileRef = useRef<InputRef>(null)
  // 处理获得验证码
  const getInputCode = () => {
    const mobile = form.getFieldValue('mobile') as string

    // 手机号右错误，焦点定位到手机输入框
    if (form.getFieldError('mobile').length > 0 || !mobile) {
      // console.log('手机号码错误')
      Toast.show({
        content: '请先输入正确的手机号码🐖',
        duration: 1000,
      })
      return mobileRef.current?.focus()
    }
    // console.log('发送验证码')
    Toast.show({
      content: '已发送',
      duration: 1000,
    })
    dispatch(getCode(mobile))
    setTimeCode(30)
  }

  // 验证码倒计时
  const [timeCode, setTimeCode] = useState(0)
  // 每次都清除上次的定时器
  useEffect(() => {
    if (timeCode === 0) return
    const timerId = window.setInterval(() => {
      setTimeCode(timeCode - 1)
    }, 1000)
    return () => {
      // 每次数据变化，清除上次引入的计时器
      console.log('清除了定时器')
      clearInterval(timerId)
    }
  }, [timeCode])
  return (
    <div className={styles.root}>
      {/* 顶层导航 */}
      <NavBar onBack={back}></NavBar>

      {/* 表单区域 */}
      <div className="login-form">
        <h2 className="title">账号登录</h2>

        <Form form={form} onFinish={onFinish}>
          <Form.Item
            name={'mobile'}
            className="login-item"
            validateTrigger={['onBlur', 'onChange']}
            rules={[
              {
                required: true,
                message: '请输入手机号',
              },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '手机号格式错误',
              },
            ]}>
            <Input
              ref={mobileRef}
              placeholder="请输入手机号"
              // 把下拉框的提示干掉
              autoComplete="off"
              // 最大长度为11位
              maxLength={11}
            />
          </Form.Item>

          <Form.Item
            name="code"
            className="login-item"
            rules={[
              { required: true, message: '请输入验证码' },
              { len: 6, message: '验证码需要6位' },
            ]}
            extra={
              <div
                className="code-extra"
                onClick={timeCode === 0 ? getInputCode : undefined}>
                {timeCode === 0 ? '发送验证码' : '还有' + timeCode + '秒'}
              </div>
            }>
            <Input
              placeholder="请输入验证码"
              autoComplete="off"
              maxLength={6}
            />
          </Form.Item>

          {/* noStyle 表示不提供 Form.Item 自带的样式 */}
          <Form.Item noStyle shouldUpdate>
            {() => {
              const isAllTouched = form.isFieldsTouched(true)
              // 是否每个验证字段都没有错误
              // console.log('表单发生变化了')
              const noError = form
                .getFieldsError()
                .every((item) => item.errors.length === 0)
              // console.log(noError) // true or false
              return (
                <Button
                  disabled={
                    !form.isFieldsTouched(true) ||
                    !!form
                      .getFieldsError()
                      .some(({ errors }) => errors.length > 0)
                  }
                  block
                  type="submit"
                  color="primary"
                  className="login-submit">
                  登录
                </Button>
              )
            }}
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
